import Vue from 'vue';
import ElementUI from 'element-ui';
import { whaleStore, whaleRouter, WhaleXHR } from '@/whale';
import App from '@/modules/app';
import vueMoment from 'vue-moment';
import '@/styles/default/index.scss';

Vue.use(ElementUI);
Vue.use(vueMoment);

const loadingInstance = Vue.prototype.$loading({
    fullscreen: true,
    lock: true
});

// 注册全局ajax方法 -- > whaleXHR
const xhr = new WhaleXHR({
    config: {
        // 配置全局接口前缀
        baseURL: '/admin',
        // 配置全局接口延迟
        timeout: 0,
        // 配置全局接口请求头 ...其他更多配置项可以参考axios文档  
        headers: {}
    },
    intercept: {
        // 配置全局SWXHR拦截器 -- > 请求前
        request(p) {
            // console.log('请求前');
            return p;
        },
        // 配置全局SWXHR拦截器 -- > 请求后
        response(res) {
            var result = res.data;
            if (result.code !== 'success') {
                Vue.prototype.$message({
                    showClose: true,
                    message: result.message,
                    type: 'warning'
                });
            }

            return result;
        }
    }
}, whaleStore);

whaleRouter.beforeEach((to, from, next) => {
    if (to.name !== 'Login') {
        let loginInfo = window.localStorage.getItem('loginInfo');
        if (!loginInfo) {
            xhr.GET('/admin/login/sessionInfo')
                .then((res) => {
                    loadingInstance.close();
                    if (res.code === 'success') {
                        window.localStorage.setItem('loginInfo', res.data);
                        next();
                    } else {
                        if (to.name !== 'Main') {
                            this.$message({
                                showClose: true,
                                message: '尚未登录，请先登录',
                                type: 'warning'
                            });
                        }
                        next({ path: '/login' });
                    }
                });
        } else {
            loadingInstance.close();
            next();
        }
    } else {
        loadingInstance.close();
        next();
    }
});


whaleStore.dispatch('initLang').then(i18n => {
    new Vue({
        el: '#app',
        router: whaleRouter,
        store: whaleStore,
        i18n,
        template: '<App/>',
        components: { App }
    });
});

// webpack热加载
if (module.hot) { module.hot.accept(); };
